package spring.cloud.tasks.tasks_manager.tasks_manager.task_item_allot.executor.task;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import spring.cloud.tasks.tasks_manager.tasks_manager.service.AllotTaskItemService;
import spring.cloud.tasks.tasks_manager.tasks_manager.task_item_allot.TaskItemAllotTask;
import spring.cloud.tasks.tasks_manager.tasks_manager.task_item_allot.executor.Executor;
import spring.cloud.tasks.tasks_manager.tasks_manager.task_item_allot.task.TaskItem;

import java.util.Iterator;
import java.util.List;

/**
 * 作业的executor下线，将该executor运行的该作业分片都摘取，如果是本地作业，则移除
 */
@Slf4j
@Setter
@Getter
public class TaskExecutorOfflineTaskItemAllotTask extends TaskItemAllotTask {

    private String taskId;

    private String executorId;

    public TaskExecutorOfflineTaskItemAllotTask(AllotTaskItemService allotTaskItemService, String taskId, String executorId) {
        super(allotTaskItemService);
        this.taskId = taskId;
        this.executorId = executorId;
    }

    @Override
    protected void logStartInfo() {
        log.info("Execute the {}, jobName is {}, executorName is {}", this.getClass().getSimpleName(), taskId, executorId);
    }

    /**
     * 只需要对onlineExecutorList进行处理即可。 onlineOwnTrafficExecutorList是onlineExecutorList共用相同的对象
     *
     * @param taskIdList                   该域下所有作业
     * @param enableTaskIdList             该域下所有启用的作业
     * @param taskItemList                 默认为空集合
     * @param onlineExecutorList           默认为当前存储的数据，如果不想使用存储数据，请重写{@link #customLastOnlineExecutorList()}}方法
     * @param onlineOwnTrafficExecutorList lastOnlineExecutorList中所有noTraffic为false的Executor，注意Executor是同一个对象
     * @return
     * @throws Exception
     */
    @Override
    protected boolean pick(List<String> taskIdList,//
                           List<String> enableTaskIdList,//
                           List<TaskItem> taskItemList,//
                           List<Executor> onlineExecutorList,//
                           List<Executor> onlineOwnTrafficExecutorList) throws Exception {
        for (int i = 0; i < onlineExecutorList.size(); i++) {
            Executor executor = onlineExecutorList.get(i);
            if (!executor.getExecutorId().equals(executorId)) {
                continue;
            }
            Iterator<TaskItem> iterator = executor.getTaskItemList().iterator();
            while (iterator.hasNext()) {
                TaskItem taskItem = iterator.next();
                if (taskItem.getTaskId().equals(taskId)) {
                    taskItemList.add(taskItem);
                    iterator.remove();
                }
            }
            executor.getTaskIdList().remove(taskId);
            break;
        }
        return true;
    }

}
